import { getValidDate } from '@/dataTransfer/coupon';
import shopBtnImg from '@/images/common/shopIcon.png';
import { debounce } from '@/utils/helper.js';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import { dateFormat } from '@/utils/time.js';
import { Image, ScrollView, View } from '@tarojs/components';
import React, { useCallback, useEffect } from 'react';
import { connect } from 'react-redux';
import GiftCardBackground from '../giftCardBackground';
import ListEnd from '../giftCardDetail/listEnd';
import './index.scss';

const OrderItem = ({ item, appConfig }) => {
  const { amount, orderTime, cardName } = item;
  return (
    <View className="order-item">
      <View className="top">
        <Image src={shopBtnImg} className="shop-logo" />
        <View className="shop-name omit">{appConfig?.name}</View>
      </View>

      <View className="bottom">
        <View className="card-logo">
          <GiftCardBackground className="inner-logo" {...item}></GiftCardBackground>
        </View>

        <View className="order-detail">
          <View className="card-name">{cardName}</View>

          <View className="order-time">{dateFormat(getValidDate(orderTime), 'yyyy-MM-dd')}</View>

          <View className="space-around-line">
            <View className="card-price">¥ {amount}</View>
            <View className="card-nu">x1</View>
          </View>
        </View>
      </View>
    </View>
  );
};

const GiftCardOrderList = ({ dispatch, loading, orderListFinished, orderList, appConfig }) => {
  useShowLoading(loading, ['giftCard/fetchOrderList']);

  // 获取记录
  const getNextList = useCallback((params) => {
    return dispatch({
      type: 'giftCard/fetchOrderList',
      payload: { pageSize: 10, ...params },
    });
  }, []);

  // 滚动获取
  const handleScrollToLower = debounce(() => {
    !orderListFinished && orderList?.length > 0 && getNextList();
  }, 1200);

  // 首次进入获取数据
  useEffect(() => {
    getNextList({ page: 1 });
  }, []);

  return (
    <>
      <ScrollView
        className="giftCardOrderList"
        enableFlex
        scrollY
        onScrollToLower={handleScrollToLower}
      >
        {orderList?.map((item, index) => {
          return <OrderItem key={index} item={item} appConfig={appConfig}></OrderItem>;
        })}

        {orderListFinished && <ListEnd />}
      </ScrollView>
    </>
  );
};
export default connect(({ loading, giftCard, otherApi }) => ({
  loading,
  orderListFinished: giftCard.orderListFinished,
  orderList: giftCard.orderList,

  appConfig: otherApi.appConfig,
}))(GiftCardOrderList);
